//
//  OosUserEntryParser.m
//  oos4ios
//
//  Created by Pablo Gonzalez on 4/12/11.
//  Copyright 2011 11870.com. All rights reserved.
//

#import "OosUserEntryParser.h"
#import <oos4ios/Model/OosAvatarImage.h>
#import <oos4ios/Oos4ios.h>

@implementation OosUserEntryParser

static OosUserEntryParser *instance;

+ (OosUserEntryParser *)instance
{
    if (!instance) {
        instance = [[OosUserEntryParser alloc] init];
    }
    return instance;
}

- (id)parseEntry:(OosEntry *)entry
{
    id result = nil;
    if ([entry isKindOfClass:[OosUserEntry class]] 
        && ((OosUserEntry *)entry).slug != nil) {
        OosUserEntry *userEntry = (OosUserEntry *) entry;
        NSString *userSlug = [entry.slug stringValue];
        OosUser *user = nil;
        OosMe *me = nil;
        if (!userEntry.name) {
            user = [OosUser userFromSlug: userSlug];
        } else {
            me = [OosMe me];
            if (me == nil) {
                me = [OosMe meFromSlug: userSlug];
            }
            user = me;
        }
        result = [self populateUser:user fromEntry:userEntry];
        if (me) {
            me.name = userEntry.name;
            me.surname = userEntry.surname;
            me.telephone = userEntry.telephone;
            me.mail = userEntry.mail;
            NSString *edit; 
            edit = [userEntry linkWithRelAttributeValue:@"edit-media"].href;
            me.editAvatarUrlString = edit;
            me.facebook = [NSNumber numberWithBool: userEntry.facebook];
            me.twitter = [NSNumber numberWithBool: userEntry.twitter];
            me.fbCheckin = [NSNumber numberWithBool: userEntry.fbCheckin];
        }
        NSError *error = nil;
        if(![me.managedObjectContext save:&error]) {
            NSLog(@"error creating OosMe: %@", [error localizedDescription]);
        }
    }
    return result;
}

- (OosUser *)populateUser:(OosUser *)user 
         fromEntry:(OosUserEntry *)entry
{
    user.nick = [entry.title stringValue];
    NSString *avatarUrlString = entry.oosAuthor.avatarUrl;
    user.avatar = [OosAvatarImage avatarFromPath:avatarUrlString];
    NSString *webUrl = [entry linkWithRelAttributeValue:@"alternate"].href;
    user.webUrlString = webUrl;
    return user;
}

@end
